package com.luminary.demo.business.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.luminary.common.framework.core.exception.SysException;
import com.luminary.common.framework.dao.GenericDao;
import com.luminary.common.framework.service.impl.GenericServiceImpl;
import com.luminary.demo.business.client.UserClient;
import com.luminary.demo.business.dao.BusinessDao;
import com.luminary.demo.business.model.po.Business;
import com.luminary.demo.business.service.BusinessService;
import com.luminary.demo.user.model.po.User;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;

@Service
public class BusinessServiceImpl extends GenericServiceImpl<Business, Integer> implements BusinessService {

	@Autowired
	private BusinessDao businessDao;
	
	@Autowired
	private UserClient userClient;
	
	@Override
	protected GenericDao<Business, Integer> getGenericDao() {
		return this.businessDao;
	}
	
	@HystrixCommand(
			fallbackMethod="findByUserFallback",
			commandKey="findByUser",
			groupKey="businessGroup",
            threadPoolKey="findByUserThread",
            ignoreExceptions=Exception.class,
            commandProperties = {
            	@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "10000"),
            	@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),
                @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "10")
        }
	)
	@Override
	@Transactional
	public Business findByUser(String username) throws Exception {
	   User user = userClient.getUser(username);
	   if(user == null) {
		   throw new SysException("500", "获取用户信息失败");
	   } 
		   
	   return businessDao.selectByUserId(user.getId());
    }
	
	public Business findByUserFallback(String username) throws Exception {
	   Business business = new Business();
	   business.setContent("默认信息");
	   return business;
	}

}
